package com.itheima.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.pojo.Result;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//登录拦截器
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    //在controller方法之前执行，返回true表示放行，返回false表示拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //log.info("LoginInterceptor拦截器执行了...");

        //1.从请求头中获取Token令牌
        String jwt = request.getHeader("Token");

        //2.使用Jwts解析令牌
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey("itheima")//设置密钥，和登录时生成的jwt一致
                    .parseClaimsJws(jwt)
                    .getBody();
            log.info("当前用户信息:{}", claims);
        } catch (Exception e) {
            //e.printStackTrace();//将异常打印到控制台
            log.error("用户未登录，禁止访问");

            //将Result转json输出给浏览器（需要自己导入fastjson坐标）如果检测到用户未登录，则会返回如下固定错误信息
            Result error = Result.error("NOT_LOGIN");
            response.getWriter().write(JSON.toJSONString(error));//响应数据

            return false;//正常返回false即可，还要响应数据告诉前端未登录不能访问
        }
        return true;//放行
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("controller方法执行完毕之后。。。执行");
    }
}
